﻿// (c) Copyright Clovis Coli Jr.
// This source is subject to the Microsoft Public License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.

using System;
using System.Windows;
using System.Windows.Controls;

namespace BrasilFramework.Controle.WPF.Comum.Validacao
{
    public class CompareValidator : ValidatorBase
    {
        public FrameworkElement ElementToCompare
        {
            get { return  (FrameworkElement) GetValue(ElemetToCompareProperty); }
            set { SetValue(ElemetToCompareProperty, value); }
        }

        public static readonly DependencyProperty ElemetToCompareProperty =
            DependencyProperty.Register(
                "ElementToCompare",
                typeof (FrameworkElement),
                typeof (CompareValidator),
                new PropertyMetadata(DependencyProperty.UnsetValue));       
        
        protected override bool ValidateControl()
        {
            if (ElementToCompare == null)
            {
                System.Diagnostics.Debug.WriteLine("ElementToCompare deve ser definido");
                throw new Exception("ElementToCompare deve ser definido");
            }

            if (!ElementsAreSameType())
            {
                System.Diagnostics.Debug.WriteLine(String.Format("Tipo do 'ElementToValidade' ({0}) não é o mesmo de 'ElementToCompare' ({1})", ElementToValidate.GetType(), ElementToCompare.GetType()));
                throw new Exception(String.Format("Tipo do 'ElementToValidade' ({0}) não é o mesmo de 'ElementToCompare' ({1})", ElementToValidate.GetType(), ElementToCompare.GetType()));
            }

            if (ElementToValidate is System.Windows.Controls.TextBox)
            {
                var boxElement = ElementToValidate as System.Windows.Controls.TextBox;
                var boxCompare = ElementToCompare as System.Windows.Controls.TextBox;

                if (boxCompare != null) 
                    return boxElement.Text.Equals(boxCompare.Text);
            }

            if (ElementToValidate is PasswordBox)
            {
                var boxElement = ElementToValidate as PasswordBox;
                var boxCompare = ElementToCompare as PasswordBox;

                if (boxCompare != null) 
                    return boxElement.Password.Equals(boxCompare.Password);
            }

            return false;
        }

        private bool ElementsAreSameType()
        {
            return ElementToValidate.GetType().IsInstanceOfType(ElementToCompare);
        }
    }
}